#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配送管理模块
负责配送网络优化和配送订单管理
"""

import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime, timedelta
import random
import math

class DeliveryManager:
    def __init__(self, data_manager):
        self.data_manager = data_manager
        
    def create_ui(self, parent):
        """创建配送管理界面"""
        # 主框架
        main_frame = tk.Frame(parent, bg='white')
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 标题
        title_label = tk.Label(main_frame, text="配送管理", 
                              font=('微软雅黑', 16, 'bold'),
                              bg='white', fg='#2c3e50')
        title_label.pack(pady=10)
        
        # 创建左右分割的界面
        content_frame = tk.Frame(main_frame, bg='white')
        content_frame.pack(fill='both', expand=True)
        
        # 左侧：配送订单管理
        left_frame = tk.Frame(content_frame, bg='white')
        left_frame.pack(side='left', fill='both', expand=True, padx=(0, 10))
        
        # 配送订单标题
        order_title = tk.Label(left_frame, text="配送订单管理", 
                              font=('微软雅黑', 14, 'bold'),
                              bg='white', fg='#2c3e50')
        order_title.pack(pady=10)
        
        # 操作按钮框架
        button_frame = tk.Frame(left_frame, bg='white')
        button_frame.pack(fill='x', pady=10)
        
        tk.Button(button_frame, text="新增配送订单", 
                 command=self.add_delivery_order_dialog,
                 font=('微软雅黑', 9),
                 bg='#27ae60', fg='white',
                 width=12).pack(side='left', padx=2)
        
        tk.Button(button_frame, text="修改订单", 
                 command=self.edit_delivery_order_dialog,
                 font=('微软雅黑', 9),
                 bg='#3498db', fg='white',
                 width=12).pack(side='left', padx=2)
        
        tk.Button(button_frame, text="删除订单", 
                 command=self.delete_delivery_order,
                 font=('微软雅黑', 9),
                 bg='#e74c3c', fg='white',
                 width=12).pack(side='left', padx=2)
        
        tk.Button(button_frame, text="路径优化", 
                 command=self.optimize_delivery_route,
                 font=('微软雅黑', 9),
                 bg='#f39c12', fg='white',
                 width=12).pack(side='left', padx=2)
        
        # 搜索框架
        search_frame = tk.Frame(left_frame, bg='white')
        search_frame.pack(fill='x', pady=5)
        
        tk.Label(search_frame, text="搜索:", font=('微软雅黑', 9),
                bg='white').pack(side='left', padx=5)
        
        self.search_var = tk.StringVar()
        search_entry = tk.Entry(search_frame, textvariable=self.search_var,
                               font=('微软雅黑', 9), width=15)
        search_entry.pack(side='left', padx=5)
        search_entry.bind('<KeyRelease>', self.on_search)
        
        # 状态筛选
        tk.Label(search_frame, text="状态:", font=('微软雅黑', 9),
                bg='white').pack(side='left', padx=(10, 5))
        
        self.status_var = tk.StringVar(value="全部")
        status_combo = ttk.Combobox(search_frame, textvariable=self.status_var,
                                   values=["全部", "待配送", "配送中", "已送达", "已完成"],
                                   width=8, state="readonly")
        status_combo.pack(side='left', padx=5)
        status_combo.bind('<<ComboboxSelected>>', self.on_search)
        
        # 配送订单列表
        list_frame = tk.Frame(left_frame, bg='white')
        list_frame.pack(fill='both', expand=True, pady=5)
        
        columns = ("订单号", "餐厅", "仓库", "配送日期", "总金额", "配送费", "状态")
        self.tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题和宽度
        column_widths = [80, 100, 80, 80, 80, 60, 60]
        for i, (col, width) in enumerate(zip(columns, column_widths)):
            self.tree.heading(col, text=col)
            self.tree.column(col, width=width, anchor='center')
        
        # 滚动条
        scrollbar_y = ttk.Scrollbar(list_frame, orient='vertical', command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar_y.set)
        
        # 布局
        self.tree.pack(side='left', fill='both', expand=True)
        scrollbar_y.pack(side='right', fill='y')
        
        # 右侧：配送网络和统计
        right_frame = tk.Frame(content_frame, bg='white')
        right_frame.pack(side='right', fill='both', expand=True, padx=(10, 0))
        
        # 配送网络标题
        network_title = tk.Label(right_frame, text="配送网络分析", 
                                font=('微软雅黑', 14, 'bold'),
                                bg='white', fg='#2c3e50')
        network_title.pack(pady=10)
        
        # 配送统计
        stats_frame = tk.LabelFrame(right_frame, text="配送统计", 
                                   font=('微软雅黑', 11, 'bold'),
                                   bg='white', fg='#3498db')
        stats_frame.pack(fill='x', pady=5)
        
        self.stats_text = tk.Text(stats_frame, height=8, width=35,
                                 font=('微软雅黑', 9),
                                 bg='#f8f9fa', fg='#2c3e50',
                                 relief='flat', wrap='word')
        self.stats_text.pack(padx=10, pady=10, fill='x')
        
        # 配送网络图
        network_frame = tk.LabelFrame(right_frame, text="配送网络图", 
                                     font=('微软雅黑', 11, 'bold'),
                                     bg='white', fg='#e74c3c')
        network_frame.pack(fill='both', expand=True, pady=5)
        
        # 创建简单的网络图显示
        self.canvas = tk.Canvas(network_frame, bg='white', height=300)
        self.canvas.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 加载数据
        self.refresh_data()
        
    def refresh_data(self):
        """刷新所有数据"""
        self.refresh_delivery_list()
        self.update_delivery_statistics()
        self.draw_delivery_network()
        
    def refresh_delivery_list(self):
        """刷新配送订单列表"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
            
        # 获取订单数据
        orders = self.data_manager.get_delivery_orders()
        
        # 应用搜索和筛选
        search_text = self.search_var.get().lower()
        status_filter = self.status_var.get()
        
        for order in orders:
            # 搜索筛选
            if search_text and search_text not in order["restaurant_name"].lower():
                continue
                
            # 状态筛选
            if status_filter != "全部" and order["status"] != status_filter:
                continue
                
            self.tree.insert('', 'end', values=(
                order["id"],
                order["restaurant_name"],
                order["warehouse_name"],
                order["delivery_date"],
                f"¥{order['total_amount']:.2f}",
                f"¥{order['delivery_cost']}",
                order["status"]
            ))
            
    def on_search(self, event=None):
        """搜索事件处理"""
        self.refresh_delivery_list()
        
    def update_delivery_statistics(self):
        """更新配送统计信息"""
        self.stats_text.delete(1.0, tk.END)
        
        orders = self.data_manager.get_delivery_orders()
        
        if not orders:
            self.stats_text.insert(tk.END, "暂无配送数据")
            return
        
        # 基本统计
        total_orders = len(orders)
        total_amount = sum(order['total_amount'] for order in orders)
        total_delivery_cost = sum(order['delivery_cost'] for order in orders)
        avg_delivery_cost = total_delivery_cost / total_orders if total_orders > 0 else 0
        
        # 状态统计
        status_stats = {}
        for order in orders:
            status = order['status']
            status_stats[status] = status_stats.get(status, 0) + 1
        
        stats_msg = f"📊 配送统计概览\n\n"
        stats_msg += f"配送订单总数: {total_orders}\n"
        stats_msg += f"配送总金额: ¥{total_amount:,.2f}\n"
        stats_msg += f"配送总成本: ¥{total_delivery_cost:,.2f}\n"
        stats_msg += f"平均配送成本: ¥{avg_delivery_cost:.2f}\n\n"
        
        stats_msg += "📋 订单状态统计:\n"
        for status, count in status_stats.items():
            percentage = (count / total_orders) * 100
            stats_msg += f"• {status}: {count}单 ({percentage:.1f}%)\n"
        
        self.stats_text.insert(tk.END, stats_msg)
        self.stats_text.config(state='disabled')
        
    def draw_delivery_network(self):
        """绘制配送网络图"""
        self.canvas.delete("all")
        
        # 获取仓库和餐厅数据
        warehouses = self.data_manager.get_warehouses()
        restaurants = self.data_manager.get_restaurants()
        
        if not warehouses or not restaurants:
            self.canvas.create_text(150, 150, text="暂无网络数据", 
                                   font=('微软雅黑', 12), fill='gray')
            return
        
        # 更新画布尺寸
        self.canvas.update()
        canvas_width = self.canvas.winfo_width() if self.canvas.winfo_width() > 1 else 400
        canvas_height = self.canvas.winfo_height() if self.canvas.winfo_height() > 1 else 300
        
        # 绘制背景网格
        self._draw_background_grid(canvas_width, canvas_height)
        
        # 计算节点位置
        warehouse_positions = self._calculate_warehouse_positions(warehouses, canvas_width, canvas_height)
        restaurant_positions = self._calculate_restaurant_positions(restaurants, canvas_width, canvas_height)
        
        # 绘制配送路径（在节点之前绘制，避免覆盖）
        self._draw_delivery_routes(warehouse_positions, restaurant_positions)
        
        # 绘制仓库节点
        self._draw_warehouses(warehouses, warehouse_positions)
        
        # 绘制餐厅节点
        self._draw_restaurants(restaurants, restaurant_positions)
        
        # 绘制图例
        self._draw_legend(canvas_width, canvas_height)
        
        # 绘制标题
        self.canvas.create_text(canvas_width // 2, 20, text="配送网络拓扑图", 
                               font=('微软雅黑', 14, 'bold'), fill='#2c3e50')
        
    def _draw_background_grid(self, width, height):
        """绘制背景网格"""
        # 绘制浅色网格线
        grid_size = 30
        for x in range(0, width, grid_size):
            self.canvas.create_line(x, 0, x, height, fill='#f0f0f0', width=1)
        for y in range(0, height, grid_size):
            self.canvas.create_line(0, y, width, y, fill='#f0f0f0', width=1)
            
    def _calculate_warehouse_positions(self, warehouses, canvas_width, canvas_height):
        """计算仓库位置"""
        positions = {}
        warehouse_y = canvas_height * 0.25  # 仓库位于上方1/4处
        
        if len(warehouses) == 1:
            x = canvas_width // 2
            positions[warehouses[0]['id']] = (x, warehouse_y)
        else:
            spacing = (canvas_width - 120) / (len(warehouses) - 1) if len(warehouses) > 1 else 0
            for i, warehouse in enumerate(warehouses):
                x = 60 + i * spacing
                positions[warehouse['id']] = (x, warehouse_y)
                
        return positions
        
    def _calculate_restaurant_positions(self, restaurants, canvas_width, canvas_height):
        """计算餐厅位置"""
        positions = {}
        restaurant_y = canvas_height * 0.75  # 餐厅位于下方3/4处
        
        if len(restaurants) == 1:
            x = canvas_width // 2
            positions[restaurants[0]['id']] = (x, restaurant_y)
        else:
            spacing = (canvas_width - 120) / (len(restaurants) - 1) if len(restaurants) > 1 else 0
            for i, restaurant in enumerate(restaurants):
                x = 60 + i * spacing
                positions[restaurant['id']] = (x, restaurant_y)
                
        return positions
        
    def _draw_warehouses(self, warehouses, positions):
        """绘制仓库节点"""
        for warehouse in warehouses:
            if warehouse['id'] in positions:
                x, y = positions[warehouse['id']]
                
                # 绘制仓库图标（蓝色六边形）
                points = []
                radius = 20
                for i in range(6):
                    angle = i * 60 * 3.14159 / 180
                    px = x + radius * math.cos(angle)
                    py = y + radius * math.sin(angle)
                    points.extend([px, py])
                
                self.canvas.create_polygon(points, fill='#3498db', outline='#2980b9', width=3)
                
                # 绘制仓库图标内的符号
                self.canvas.create_text(x, y, text="仓", font=('微软雅黑', 10, 'bold'), fill='white')
                
                # 绘制仓库名称
                self.canvas.create_text(x, y - 35, text=warehouse['name'], 
                                       font=('微软雅黑', 9, 'bold'), fill='#2c3e50')
                
                # 绘制容量信息
                capacity_text = f"{warehouse['current_stock']}/{warehouse['capacity']}"
                self.canvas.create_text(x, y + 35, text=capacity_text, 
                                       font=('微软雅黑', 8), fill='#7f8c8d')
                
    def _draw_restaurants(self, restaurants, positions):
        """绘制餐厅节点"""
        for restaurant in restaurants:
            if restaurant['id'] in positions:
                x, y = positions[restaurant['id']]
                
                # 绘制餐厅图标（绿色圆角矩形）
                self.canvas.create_rounded_rectangle(x-18, y-15, x+18, y+15, 
                                                   radius=8, fill='#27ae60', outline='#229954', width=3)
                
                # 绘制餐厅图标内的符号
                self.canvas.create_text(x, y, text="餐", font=('微软雅黑', 10, 'bold'), fill='white')
                
                # 绘制餐厅名称
                self.canvas.create_text(x, y + 30, text=restaurant['name'], 
                                       font=('微软雅黑', 9, 'bold'), fill='#2c3e50')
                
                # 绘制经理信息
                self.canvas.create_text(x, y + 45, text=restaurant['manager'], 
                                       font=('微软雅黑', 8), fill='#7f8c8d')
                
    def _draw_delivery_routes(self, warehouse_positions, restaurant_positions):
        """绘制配送路径"""
        orders = self.data_manager.get_delivery_orders()
        
        # 统计路径使用频率
        route_counts = {}
        for order in orders:
            if order['warehouse_id'] in warehouse_positions and order['restaurant_id'] in restaurant_positions:
                route_key = (order['warehouse_id'], order['restaurant_id'])
                route_counts[route_key] = route_counts.get(route_key, 0) + 1
        
        # 绘制路径
        for order in orders:
            if order['warehouse_id'] in warehouse_positions and order['restaurant_id'] in restaurant_positions:
                w_pos = warehouse_positions[order['warehouse_id']]
                r_pos = restaurant_positions[order['restaurant_id']]
                
                # 根据订单状态设置线条颜色和样式
                if order['status'] == '已完成':
                    color = '#27ae60'
                    width = 3
                    dash = None
                elif order['status'] == '配送中':
                    color = '#f39c12'
                    width = 4
                    dash = (8, 4)
                elif order['status'] == '已送达':
                    color = '#3498db'
                    width = 3
                    dash = (4, 2)
                else:
                    color = '#95a5a6'
                    width = 2
                    dash = (6, 6)
                
                # 绘制带箭头的路径线
                self._draw_arrow_line(w_pos[0], w_pos[1], r_pos[0], r_pos[1], 
                                    color, width, dash)
                
                # 在路径中点显示配送费用
                mid_x = (w_pos[0] + r_pos[0]) // 2
                mid_y = (w_pos[1] + r_pos[1]) // 2
                
                # 绘制费用标签背景
                self.canvas.create_oval(mid_x-12, mid_y-8, mid_x+12, mid_y+8, 
                                       fill='white', outline=color, width=2)
                self.canvas.create_text(mid_x, mid_y, text=f"¥{order['delivery_cost']}", 
                                       font=('微软雅黑', 7), fill=color)
                
    def _draw_arrow_line(self, x1, y1, x2, y2, color, width, dash):
        """绘制带箭头的线条"""
        # 绘制主线条
        if dash:
            self.canvas.create_line(x1, y1, x2, y2, fill=color, width=width, dash=dash)
        else:
            self.canvas.create_line(x1, y1, x2, y2, fill=color, width=width)
        
        # 计算箭头位置
        dx = x2 - x1
        dy = y2 - y1
        length = math.sqrt(dx*dx + dy*dy)
        
        if length > 0:
            # 单位向量
            ux = dx / length
            uy = dy / length
            
            # 箭头位置（距离终点20像素）
            arrow_x = x2 - 20 * ux
            arrow_y = y2 - 20 * uy
            
            # 箭头的两个边
            arrow_size = 8
            perp_x = -uy * arrow_size
            perp_y = ux * arrow_size
            
            # 绘制箭头
            self.canvas.create_polygon([
                x2, y2,
                arrow_x + perp_x, arrow_y + perp_y,
                arrow_x - perp_x, arrow_y - perp_y
            ], fill=color, outline=color)
            
    def _draw_legend(self, canvas_width, canvas_height):
        """绘制图例"""
        legend_x = canvas_width - 120
        legend_y = 50
        
        # 图例背景
        self.canvas.create_rectangle(legend_x - 10, legend_y - 10, 
                                   canvas_width - 10, legend_y + 120, 
                                   fill='#f8f9fa', outline='#dee2e6', width=2)
        
        # 图例标题
        self.canvas.create_text(legend_x + 40, legend_y + 5, text="图例", 
                               font=('微软雅黑', 10, 'bold'), fill='#2c3e50')
        
        # 仓库图例
        legend_y += 25
        points = []
        radius = 8
        for i in range(6):
            angle = i * 60 * 3.14159 / 180
            px = legend_x + radius * math.cos(angle)
            py = legend_y + radius * math.sin(angle)
            points.extend([px, py])
        self.canvas.create_polygon(points, fill='#3498db', outline='#2980b9', width=2)
        self.canvas.create_text(legend_x + 25, legend_y, text="仓库", 
                               font=('微软雅黑', 8), fill='#2c3e50')
        
        # 餐厅图例
        legend_y += 20
        self.canvas.create_rounded_rectangle(legend_x-8, legend_y-6, legend_x+8, legend_y+6, 
                                           radius=4, fill='#27ae60', outline='#229954', width=2)
        self.canvas.create_text(legend_x + 25, legend_y, text="餐厅", 
                               font=('微软雅黑', 8), fill='#2c3e50')
        
        # 配送状态图例
        legend_y += 20
        statuses = [
            ("已完成", "#27ae60", None),
            ("配送中", "#f39c12", (4, 2)),
            ("已送达", "#3498db", (2, 1)),
            ("待配送", "#95a5a6", (3, 3))
        ]
        
        for status, color, dash in statuses:
            if dash:
                self.canvas.create_line(legend_x-5, legend_y, legend_x+10, legend_y, 
                                       fill=color, width=2, dash=dash)
            else:
                self.canvas.create_line(legend_x-5, legend_y, legend_x+10, legend_y, 
                                       fill=color, width=2)
            self.canvas.create_text(legend_x + 25, legend_y, text=status, 
                                   font=('微软雅黑', 7), fill='#2c3e50')
            legend_y += 15

    def add_delivery_order_dialog(self):
        """新增配送订单对话框"""
        dialog = tk.Toplevel()
        dialog.title("新增配送订单")
        dialog.geometry("600x700")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 订单号（自动生成）
        row = 0
        tk.Label(form_frame, text="订单号:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        order_id = f"DO{str(len(self.data_manager.get_delivery_orders()) + 1).zfill(4)}"
        tk.Label(form_frame, text=order_id, font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 餐厅选择
        row += 1
        tk.Label(form_frame, text="目标餐厅:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        restaurant_var = tk.StringVar()
        restaurants = self.data_manager.get_restaurants()
        restaurant_names = [f"{r['name']} ({r['id']})" for r in restaurants]
        restaurant_combo = ttk.Combobox(form_frame, textvariable=restaurant_var,
                                       values=restaurant_names, width=30, state="readonly")
        restaurant_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 仓库选择
        row += 1
        tk.Label(form_frame, text="发货仓库:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        warehouse_var = tk.StringVar()
        warehouses = self.data_manager.get_warehouses()
        warehouse_names = [f"{w['name']} ({w['id']})" for w in warehouses]
        warehouse_combo = ttk.Combobox(form_frame, textvariable=warehouse_var,
                                      values=warehouse_names, width=30, state="readonly")
        warehouse_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 配送日期
        row += 1
        tk.Label(form_frame, text="配送日期:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        delivery_date_var = tk.StringVar(value=(datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d"))
        delivery_date_entry = tk.Entry(form_frame, textvariable=delivery_date_var,
                                      font=('微软雅黑', 10), width=25)
        delivery_date_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 商品选择区域
        row += 1
        tk.Label(form_frame, text="配送商品:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='nw', pady=5)
        
        # 商品列表框架
        items_frame = tk.Frame(form_frame, bg='white', relief='sunken', bd=1)
        items_frame.grid(row=row, column=1, sticky='w', pady=5)
        
        # 商品选择列表
        items_listbox_frame = tk.Frame(items_frame, bg='white')
        items_listbox_frame.pack(fill='both', expand=True, padx=5, pady=5)
        
        tk.Label(items_listbox_frame, text="可选商品:", font=('微软雅黑', 9),
                bg='white').pack(anchor='w')
        
        available_items_listbox = tk.Listbox(items_listbox_frame, height=6, width=40,
                                            font=('微软雅黑', 9))
        available_items_listbox.pack(fill='x', pady=2)
        
        # 填充可选商品
        inventory_items = self.data_manager.get_inventory_items()
        for item in inventory_items:
            available_items_listbox.insert(tk.END, f"{item['name']} - 库存:{item['current_stock']} - ¥{item['unit_price']:.2f}")
        
        # 添加商品按钮
        add_item_frame = tk.Frame(items_listbox_frame, bg='white')
        add_item_frame.pack(fill='x', pady=5)
        
        tk.Label(add_item_frame, text="数量:", font=('微软雅黑', 9),
                bg='white').pack(side='left')
        
        item_quantity_var = tk.StringVar()
        item_quantity_entry = tk.Entry(add_item_frame, textvariable=item_quantity_var,
                                      font=('微软雅黑', 9), width=10)
        item_quantity_entry.pack(side='left', padx=5)
        
        # 已选商品列表
        tk.Label(items_listbox_frame, text="已选商品:", font=('微软雅黑', 9),
                bg='white').pack(anchor='w', pady=(10, 0))
        
        selected_items_listbox = tk.Listbox(items_listbox_frame, height=6, width=40,
                                           font=('微软雅黑', 9))
        selected_items_listbox.pack(fill='x', pady=2)
        
        # 存储已选商品的列表
        selected_items = []
        
        def add_selected_item():
            selection = available_items_listbox.curselection()
            if not selection:
                messagebox.showwarning("警告", "请先选择商品")
                return
                
            if not item_quantity_var.get() or not item_quantity_var.get().isdigit():
                messagebox.showerror("错误", "请输入有效的数量")
                return
                
            quantity = int(item_quantity_var.get())
            if quantity <= 0:
                messagebox.showerror("错误", "数量必须大于0")
                return
            
            item_index = selection[0]
            item = inventory_items[item_index]
            
            if quantity > item['current_stock']:
                messagebox.showerror("错误", "数量不能超过库存")
                return
            
            # 添加到已选列表
            selected_item = {
                'item_id': item['id'],
                'item_name': item['name'],
                'quantity': quantity,
                'unit_price': item['unit_price'],
                'amount': quantity * item['unit_price']
            }
            selected_items.append(selected_item)
            
            # 更新显示
            selected_items_listbox.insert(tk.END, 
                f"{item['name']} x{quantity} = ¥{selected_item['amount']:.2f}")
            
            item_quantity_var.set("")
        
        def remove_selected_item():
            selection = selected_items_listbox.curselection()
            if selection:
                index = selection[0]
                selected_items.pop(index)
                selected_items_listbox.delete(index)
        
        button_frame = tk.Frame(items_listbox_frame, bg='white')
        button_frame.pack(fill='x', pady=5)
        
        tk.Button(button_frame, text="添加商品", command=add_selected_item,
                 font=('微软雅黑', 9), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="移除商品", command=remove_selected_item,
                 font=('微软雅黑', 9), bg='#e74c3c', fg='white',
                 width=10).pack(side='left', padx=5)
        
        # 配送费用
        row += 1
        tk.Label(form_frame, text="配送费用:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        delivery_cost_var = tk.StringVar(value="100")
        delivery_cost_entry = tk.Entry(form_frame, textvariable=delivery_cost_var,
                                      font=('微软雅黑', 10), width=25)
        delivery_cost_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 状态
        row += 1
        tk.Label(form_frame, text="状态:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        status_var = tk.StringVar(value="待配送")
        status_combo = ttk.Combobox(form_frame, textvariable=status_var,
                                   values=["待配送", "配送中", "已送达", "已完成"],
                                   width=22, state="readonly")
        status_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.grid(row=row+1, column=0, columnspan=2, pady=20)
        
        def save_order():
            try:
                # 验证输入
                if not restaurant_var.get() or not warehouse_var.get():
                    messagebox.showerror("错误", "请选择餐厅和仓库")
                    return
                    
                if not selected_items:
                    messagebox.showerror("错误", "请至少选择一个商品")
                    return
                
                # 获取餐厅和仓库ID
                restaurant_id = restaurant_var.get().split('(')[1].split(')')[0]
                restaurant_name = restaurant_var.get().split(' (')[0]
                warehouse_id = warehouse_var.get().split('(')[1].split(')')[0]
                warehouse_name = warehouse_var.get().split(' (')[0]
                
                # 计算总金额
                total_amount = sum(item['amount'] for item in selected_items)
                
                # 创建订单
                order = {
                    "id": order_id,
                    "restaurant_id": restaurant_id,
                    "restaurant_name": restaurant_name,
                    "warehouse_id": warehouse_id,
                    "warehouse_name": warehouse_name,
                    "order_date": datetime.now().strftime("%Y-%m-%d"),
                    "delivery_date": delivery_date_var.get(),
                    "items": selected_items,
                    "total_amount": total_amount,
                    "delivery_cost": int(delivery_cost_var.get()),
                    "status": status_var.get()
                }
                
                # 保存订单
                self.data_manager.add_delivery_order(order)
                messagebox.showinfo("成功", "配送订单已添加")
                dialog.destroy()
                self.refresh_data()
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
            except Exception as e:
                messagebox.showerror("错误", f"保存失败: {str(e)}")
        
        tk.Button(button_frame, text="保存", command=save_order,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(side='left', padx=10)
        
    def edit_delivery_order_dialog(self):
        """修改配送订单对话框"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要修改的订单")
            return
            
        # 获取选中的订单
        item = self.tree.item(selected[0])
        order_id = item['values'][0]
        
        # 找到对应的订单数据
        orders = self.data_manager.get_delivery_orders()
        current_order = None
        for order in orders:
            if order['id'] == order_id:
                current_order = order
                break
                
        if not current_order:
            messagebox.showerror("错误", "未找到订单数据")
            return
        
        # 创建简化的修改对话框
        dialog = tk.Toplevel()
        dialog.title("修改配送订单")
        dialog.geometry("400x300")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 订单号（只读）
        row = 0
        tk.Label(form_frame, text="订单号:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        tk.Label(form_frame, text=order_id, font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 餐厅（只读）
        row += 1
        tk.Label(form_frame, text="餐厅:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        tk.Label(form_frame, text=current_order['restaurant_name'], font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 配送日期
        row += 1
        tk.Label(form_frame, text="配送日期:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        delivery_date_var = tk.StringVar(value=current_order['delivery_date'])
        delivery_date_entry = tk.Entry(form_frame, textvariable=delivery_date_var,
                                      font=('微软雅黑', 10), width=20)
        delivery_date_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 配送费用
        row += 1
        tk.Label(form_frame, text="配送费用:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        delivery_cost_var = tk.StringVar(value=str(current_order['delivery_cost']))
        delivery_cost_entry = tk.Entry(form_frame, textvariable=delivery_cost_var,
                                      font=('微软雅黑', 10), width=20)
        delivery_cost_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 状态
        row += 1
        tk.Label(form_frame, text="状态:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        status_var = tk.StringVar(value=current_order['status'])
        status_combo = ttk.Combobox(form_frame, textvariable=status_var,
                                   values=["待配送", "配送中", "已送达", "已完成"],
                                   width=17, state="readonly")
        status_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.grid(row=row+1, column=0, columnspan=2, pady=20)
        
        def update_order():
            try:
                # 更新订单
                updated_order = current_order.copy()
                updated_order.update({
                    "delivery_date": delivery_date_var.get(),
                    "delivery_cost": int(delivery_cost_var.get()),
                    "status": status_var.get()
                })
                
                # 保存更新
                self.data_manager.update_delivery_order(order_id, updated_order)
                messagebox.showinfo("成功", "配送订单已更新")
                dialog.destroy()
                self.refresh_data()
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
            except Exception as e:
                messagebox.showerror("错误", f"更新失败: {str(e)}")
        
        tk.Button(button_frame, text="保存", command=update_order,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(side='left', padx=10)
        
    def delete_delivery_order(self):
        """删除配送订单"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要删除的订单")
            return
            
        # 获取选中的订单
        item = self.tree.item(selected[0])
        order_id = item['values'][0]
        
        if messagebox.askyesno("确认", f"确定要删除订单 {order_id} 吗？"):
            self.data_manager.delete_delivery_order(order_id)
            messagebox.showinfo("成功", "订单已删除")
            self.refresh_data()
            
    def optimize_delivery_route(self):
        """优化配送路径"""
        orders = self.data_manager.get_delivery_orders()
        pending_orders = [order for order in orders if order['status'] in ['待配送', '配送中']]
        
        if not pending_orders:
            messagebox.showinfo("提示", "当前没有需要优化的配送订单")
            return
        
        # 简单的路径优化算法（按距离排序）
        warehouses = {w['id']: w for w in self.data_manager.get_warehouses()}
        restaurants = {r['id']: r for r in self.data_manager.get_restaurants()}
        
        # 计算优化建议
        optimization_results = []
        
        for order in pending_orders:
            warehouse = warehouses.get(order['warehouse_id'])
            restaurant = restaurants.get(order['restaurant_id'])
            
            if warehouse and restaurant:
                # 简单的距离计算（基于名称长度，实际应用中应使用真实坐标）
                distance = abs(len(warehouse['name']) - len(restaurant['name'])) + random.randint(5, 20)
                estimated_time = distance * 2  # 估算时间（分钟）
                
                optimization_results.append({
                    'order_id': order['id'],
                    'restaurant': restaurant['name'],
                    'warehouse': warehouse['name'],
                    'distance': distance,
                    'estimated_time': estimated_time,
                    'current_cost': order['delivery_cost']
                })
        
        # 按距离排序
        optimization_results.sort(key=lambda x: x['distance'])
        
        # 显示优化结果
        result_dialog = tk.Toplevel()
        result_dialog.title("配送路径优化结果")
        result_dialog.geometry("600x400")
        result_dialog.configure(bg='white')
        result_dialog.transient()
        result_dialog.grab_set()
        
        # 居中显示
        result_dialog.update_idletasks()
        x = (result_dialog.winfo_screenwidth() // 2) - (result_dialog.winfo_width() // 2)
        y = (result_dialog.winfo_screenheight() // 2) - (result_dialog.winfo_height() // 2)
        result_dialog.geometry(f"+{x}+{y}")
        
        # 结果显示
        result_frame = tk.Frame(result_dialog, bg='white')
        result_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        tk.Label(result_frame, text="配送路径优化建议", 
                font=('微软雅黑', 14, 'bold'),
                bg='white', fg='#2c3e50').pack(pady=10)
        
        # 创建结果表格
        columns = ("订单号", "餐厅", "仓库", "距离", "预计时间", "当前费用", "建议")
        result_tree = ttk.Treeview(result_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题和宽度
        column_widths = [80, 100, 80, 60, 80, 80, 100]
        for i, (col, width) in enumerate(zip(columns, column_widths)):
            result_tree.heading(col, text=col)
            result_tree.column(col, width=width, anchor='center')
        
        # 填充数据
        for i, result in enumerate(optimization_results):
            priority = "高优先级" if i < len(optimization_results) // 3 else "中优先级" if i < len(optimization_results) * 2 // 3 else "低优先级"
            
            result_tree.insert('', 'end', values=(
                result['order_id'],
                result['restaurant'],
                result['warehouse'],
                f"{result['distance']}km",
                f"{result['estimated_time']}分钟",
                f"¥{result['current_cost']}",
                priority
            ))
        
        # 滚动条
        scrollbar = ttk.Scrollbar(result_frame, orient='vertical', command=result_tree.yview)
        result_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        result_tree.pack(side='left', fill='both', expand=True)
        scrollbar.pack(side='right', fill='y')
        
        # 优化建议文本
        suggestion_text = tk.Text(result_frame, height=6, width=70,
                                 font=('微软雅黑', 9),
                                 bg='#f8f9fa', fg='#2c3e50',
                                 relief='flat', wrap='word')
        suggestion_text.pack(fill='x', pady=10)
        
        suggestions = f"""
优化建议：
1. 按距离优先级安排配送顺序，优先配送距离较近的订单
2. 合并同一区域的配送订单，减少配送成本
3. 建议配送时间：高优先级订单在2小时内完成，中优先级4小时内，低优先级当日完成
4. 总计可节省配送成本约：¥{sum(r['current_cost'] for r in optimization_results) * 0.15:.2f}
5. 预计总配送时间：{sum(r['estimated_time'] for r in optimization_results)}分钟
        """
        
        suggestion_text.insert(tk.END, suggestions)
        suggestion_text.config(state='disabled')
        
        # 关闭按钮
        tk.Button(result_frame, text="关闭", command=result_dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(pady=10)

# 为Canvas添加圆角矩形方法
def create_rounded_rectangle(self, x1, y1, x2, y2, radius=10, **kwargs):
    """创建圆角矩形"""
    points = []
    
    # 确保坐标正确
    if x1 > x2:
        x1, x2 = x2, x1
    if y1 > y2:
        y1, y2 = y2, y1
        
    # 限制圆角半径
    radius = min(radius, (x2-x1)/2, (y2-y1)/2)
    
    # 生成圆角矩形的点
    # 右上角
    for i in range(0, 91, 10):
        x = x2 - radius + radius * math.cos(math.radians(i))
        y = y1 + radius - radius * math.sin(math.radians(i))
        points.extend([x, y])
    
    # 右下角
    for i in range(90, 181, 10):
        x = x2 - radius + radius * math.cos(math.radians(i))
        y = y2 - radius - radius * math.sin(math.radians(i))
        points.extend([x, y])
    
    # 左下角
    for i in range(180, 271, 10):
        x = x1 + radius + radius * math.cos(math.radians(i))
        y = y2 - radius - radius * math.sin(math.radians(i))
        points.extend([x, y])
    
    # 左上角
    for i in range(270, 361, 10):
        x = x1 + radius + radius * math.cos(math.radians(i))
        y = y1 + radius - radius * math.sin(math.radians(i))
        points.extend([x, y])
    
    return self.create_polygon(points, **kwargs)

# 将方法添加到Canvas类
tk.Canvas.create_rounded_rectangle = create_rounded_rectangle 